package core.network.marshal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class MarshalUtils
{
    public static byte[] objectToByteArray( Serializable obj )
            throws IOException {
        if( obj == null )
            return null;
        ObjectOutput out = null;
        byte[] buf = null;
        try {
            // Serialize to a byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream( bos );
            out.writeObject( obj );

            // Get the bytes of the serialized object
            buf = bos.toByteArray();

        } catch( IOException e ) {
            e.printStackTrace();
        } finally {
            if( out != null )
                out.close();
        }
        return buf;
    }

    public static Object byteArrayToObject( byte[] bytes ) throws IOException {
        ObjectInputStream in = null;
        Object obj = null;
        try {
            // Deserialize from a byte array
            in = new ObjectInputStream( new ByteArrayInputStream( bytes ) );
            obj = in.readObject();
        } catch( ClassNotFoundException e ) {
        } catch( IOException e ) {
        } finally {
            if( in != null )
                in.close();
        }
        return obj;
    }
}
